//
//  NSString+SYDES.m
//  24加密解密作业
//
//  Created by dllo on 16/8/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NSString+SYDES.h"
#import <CommonCrypto/CommonCrypto.h>
#define key @"01234567"
static Byte iv[] = {1,2,3,4,5,6,7,8};
@implementation NSString (SYDES)
- (NSString *)stringWithDES
{
    const char *string = [self UTF8String];
    unsigned char bytes[1024];
    size_t dataOutMoved = 0;
    CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, string, strlen(string), bytes, 1024, &dataOutMoved);
    if (cryptorStatus == kCCSuccess) {
        NSData *desData = [NSData dataWithBytes:bytes length:dataOutMoved];
        NSString *desBase64String = [desData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//        NSLog(@"加密成功");
        return desBase64String;
    } else {
//        NSLog(@"加密失败");
        return nil;
    }
    
    
    }
- (NSString *)desWithString
{
//    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    const void *byte = data.bytes;
//    unsigned char buffer[1024];
//    size_t dataOutMoved = 0;
//    CCCryptorStatus cryptorStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, byte, [data length], buffer, 1024, &dataOutMoved);
//    if (cryptorStatus == kCCSuccess) {
//        NSData *sourceData = [[NSData alloc] initWithBytes:byte length:dataOutMoved];
//        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
//        NSLog(@"解密成功");
//        return sourceString;
//    } else {
//        NSLog(@"解密失败");
//        return nil;
//    }
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    const void *byte = data.bytes;
    unsigned char buffer[1024];
    size_t dataOutMoved = 0;
    CCCryptorStatus ryptorStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, byte, [data length], buffer, 1024, &dataOutMoved);
    if (ryptorStatus == kCCSuccess) {
        NSLog(@"解密成功");
        NSData *sourceData = [[NSData alloc] initWithBytes:buffer length:dataOutMoved];
        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
        return sourceString;
    } else {
//        NSLog(@"解密失败");
        return nil;
    }

    
    
    
    
}
@end
